#tmp module v1.6b
def inf(support,im_types,ex_types,SC_types): pass #plugin information
def impt(imfl,imSC,debug): pass #import function
def expt(exfl,exSC,debug): pass #export function
#^functions are required for extension modules, but don't have to contain any info

#PLEASE DO NOT MODIFY THIS FILE.
#

#description:
"""This is the plugin dedicated to reading and writing the global.tmp file.
This plugin is ment to provide functions to make it easier to send and recieve data pertaining to the TMP.
All functions will have a description to notify you of how to use them.
You may also use the provided documentation on the functions if you wish."""

def setRead(): global tmpr; tmpr = open('global.tmp','r'); print 'tmp set to read'
def setWrite(): global tmpw; tmpw = open('global.tmp','w'); print 'tmp set to write'
def closeRead(): tmpr.close(); print 'tmp sucessfully closed'
def closeWrite(): """tmpw.write('!')""";tmpw.close(); print 'tmp sucessfully closed'


#pre-defined functions <!--
def setVector( VectorList, VectorType, Transform, ObjectID, Channel ):
    TypeList = [ 'vertices' , 'normals' , 'uvs' ]
    if Transform: tmpw.write( '< transform ' + TypeList[VectorType] + ' ' + str(ObjectID) + ' ' )
    else: tmpw.write( '< ' + TypeList[VectorType] + ' ' + str(ObjectID) + ' ' )
    if VectorType == 2: tmpw.write( str(int(Channel)) + ' ' )
    for Index, Vector in enumerate(VectorList):
        for VectorIndex, Value in enumerate(Vector):
            tmpw.write(str(float(Value)))
            if VectorIndex != len(Vector)-1: tmpw.write('|')
        if Index != len(VectorList)-1: tmpw.write('/')
    tmpw.write('\n')
    if Transform: print "'"+TypeList[VectorType]+"'"+' Transform vectors for object '+str(ObjectID)+' logged successfully'
    else: print "'"+TypeList[VectorType]+"'"+' Vectors for object '+str(ObjectID)+' logged successfully'
    

def getVector(VectorType, Transform, ObjectID, Channel):
    tmpr.seek(0,0)
    VectorList = []
    TypeList = [ 'vertices' , 'normals' , 'uvs' ]
    lines = tmpr.readlines()
    for line in lines:
        if Transform:
            if line.split()[1] == 'transform' and line.split()[2] == TypeList[VectorType] and line.split()[3] == str(ObjectID):
                if VectorType < 2:
                    for vector in (line.split()[4]).split('/'): VectorList.append(vector.split('|'))
                elif line.split()[4] == str(int(Channel)):
                    for vector in (line.split()[5]).split('/'): VectorList.append(vector.split('|'))
        else:
            if line.split()[1] == TypeList[VectorType] and line.split()[2] == str(ObjectID):
                if VectorType < 2:
                    for vector in (line.split()[3]).split('/'): VectorList.append(vector.split('|'))
                elif line.split()[3] == str(int(Channel)):
                    for vector in (line.split()[4]).split('/'): VectorList.append(vector.split('|'))
    if Transform: print "'"+TypeList[VectorType]+"'"+' Transform vectors for object '+str(ObjectID)+' returned sucessfully'
    else: print "'"+TypeList[VectorType]+"'"+' Vectors for object '+str(ObjectID)+' returned sucessfully'
    return VectorList
    

def setFacepoint( FacePointList ): #this function is defined for setPrimitives (do not use in your code)
    return  str(FacePointList[0]) + ':' + str(FacePointList[1]) + ':' + str(FacePointList[2]) + ':' +\
            str(FacePointList[3]) + ':' + str(FacePointList[4]) + ':' + str(FacePointList[5]) + ':' +\
            str(FacePointList[6]) + ':' + str(FacePointList[7]) + ':' + str(FacePointList[8]) + ':' +\
            str(FacePointList[9])

def getFacepoint( FacePoint ): #this function is defined for getPrimitives (do not use in your code)
    FP = FacePoint.split(':')
    Vertex = FP[0]; Normal = FP[1]
    UV0 = FP[2]; UV1 = FP[3]; UV2 = FP[4]; UV3 = FP[5]
    UV4 = FP[6]; UV5 = FP[7]; UV6 = FP[8]; UV7 = FP[9]
    return [Vertex, Normal, UV0, UV1, UV2, UV3, UV4, UV5, UV6, UV7]

def setPrimitives( PrimitivesList, ObjectID ):
    tmpw.write('< faces ' + str(int(ObjectID)) + ' ')
    for Index, Primitive in enumerate(PrimitivesList):
        FacePoints = []
        for FacePoint in Primitive[1]: FacePoints.append(setFacepoint(FacePoint))
        Primitives = [str(Primitive[0]),'|'.join(FacePoints)]
        tmpw.write(';'.join(Primitives))
        if Index != len(PrimitivesList)-1: tmpw.write('/')
    tmpw.write('\n')
    print 'Primitives for object ' + str(int(ObjectID)) + ' logged successfully'

def getPrimitives( ObjectID ):
    tmpr.seek(0,0)
    PrimitivesList = []
    lines = tmpr.readlines()
    for line in lines:
        if line.split()[1] == 'faces' and line.split()[2] == str(int(ObjectID)):
            for Primitive in (line.split()[3]).split('/'):
                FacePoints = []
                for FacePoint in (Primitive.split(';')[1]).split('|'): FacePoints.append(getFacepoint(FacePoint))
                PrimitivesList.append([int(Primitive.split(';')[0]),FacePoints])
    print 'Primitives for object ' + str(int(ObjectID)) + ' successfully returned'
    return PrimitivesList

def setBasicObject( ObjectID, ObjectName, ParentID ):
    tmpw.write('< object ' + str(ObjectID) + ' ' + ObjectName + ' ' + str(ParentID) + '\n')
    print 'Object "'+ ObjectName + '" logged successfully'

def getBasicObject( ObjectID ):
    tmpr.seek(0,0)
    lines = tmpr.readlines()
    for line in lines:
        if line.split()[1] == 'object' and line.split()[2] == str(int(ObjectID)):
            print 'Object ' + line.split()[3] + ' successfully returned'
            if len(line) == 5: return line.split()[3], line.split()[4]
            else: return line.split()[3], ''

def setBone( ObjectID, IK_ID, Layer, Name, Parent, ID, Connected, loc, sca, rot, bind, inverse ): pass #TODO

def getBone( ObjectID, BoneID ): pass #TODO

#TODO: Library Objects
#-->
    
#useful functions <!--
def applyTransforms( VectorList , TransformList ):
    if len(VectorList) == len(TransformList):
        ValueList = []
        for Index, Vector in enumerate(VectorList):
            Values = []
            Transform = TransformList[Index]
            for ValueIndex, Value in enumerate(Vector): Values.append(float(Transform[ValueIndex])+float(Value))
            ValueList.append(Values)
            print 'Transforms applied successfully'
        return ValueList
    else: print 'ERROR: invalad vector/transform list provided'

def convertToTriangles( PrimitivesList, singlePrimitive ):
    TrianglesList = []
    for Primitive in PrimitivesList:
        SingleTriangles = [] #passed if singlePrimitive = false
        if Primitive[0] == 0: #points
            if singlePrimitive: pass
            else: TrianglesList.append(Primitive)
        if Primitive[0] == 1: #lines
            if singlePrimitive: pass
            else: TrianglesList.append(Primitive)
        if Primitive[0] == 2: #line-strips
            if singlePrimitive: pass
            else: TrianglesList.append(Primitive)
        if Primitive[0] == 3: #triangles
            if singlePrimitive:
                for facepoint in Primitive[1]: SingleTriangles.append(facepoint)
            else: TrianglesList.append(Primitive)
        if Primitive[0] == 4: #tri-strips
            index = 0
            Triangles = [3,[]]
            while index != len(Primitive[1])-2:
                T1 = (Primitive[1])[index]
                T2 = (Primitive[1])[index+1]
                T3 = (Primitive[1])[index+2]
                if T1 != T2 and T1 != T3 and T2 != T3:
                    if (index % 2):
                        Triangles[1].append(T3)
                        Triangles[1].append(T2)
                        Triangles[1].append(T1)
                    else:
                        Triangles[1].append(T1)
                        Triangles[1].append(T2)
                        Triangles[1].append(T3)
                index += 1
            if singlePrimitive:
                for facepoint in Triangles[1]: SingleTriangles.append(facepoint)
            else: TrianglesList.append(Triangles)
        if Primitive[0] == 5: #tri-fans
            index = 0
            Triangles = [3,[]]
            T1 = (Primitive[1])[index]
            while index != len(Primitive[1])-2:
                T2 = (Primitive[1])[index+1]
                T3 = (Primitive[1])[index+2]
                if T1 != T2 and T1 != T3 and T2 != T3:
                    if (index % 2):
                        Triangles[1].append(T3)
                        Triangles[1].append(T2)
                        Triangles[1].append(T1)
                    else:
                        Triangles[1].append(T1)
                        Triangles[1].append(T2)
                        Triangles[1].append(T3)
                index += 1
            if singlePrimitive:
                for facepoint in Triangles[1]: SingleTriangles.append(facepoint)
            else: TrianglesList.append(Triangles)
        if Primitive[0] == 6: #quads
            index = 0
            Triangles = [3,[]]
            while index != len(Primitive[1]):
                Q1 = (Primitive[1])[index]
                Q2 = (Primitive[1])[index+1]
                Q3 = (Primitive[1])[index+2]
                Q4 = (Primitive[1])[index+3]
                Triangles[1].append(Q1)
                Triangles[1].append(Q2)
                Triangles[1].append(Q3)
                Triangles[1].append(Q2)
                Triangles[1].append(Q3)
                Triangles[1].append(Q4)
                index += 4
            if singlePrimitive:
                for facepoint in Triangles[1]: SingleTriangles.append(facepoint)
            else: TrianglesList.append(Triangles)
    if singlePrimitive: TrianglesList.append([3,SingleTriangles])
    return TrianglesList

def convertFromTriangles( TrianglesList, splitPrimitives ):
    pass
#-->

#main functions <!--
def setObject( ObjectID, ObjectName, ParentID, VectorsList, PrimitivesList, BonesList ):
    if VectorsList != [] and BonesList == []:
        vert = VectorsList[0]
        normal = VectorsList[1]
        UVs = [VectorsList[2],VectorsList[3],VectorsList[4],VectorsList[5],VectorsList[6],VectorsList[7],VectorsList[8],VectorsList[9]]
        trans_vert = VectorsList[10]
        trans_normal = VectorsList[11]
        trans_UVs = [VectorsList[12],VectorsList[13],VectorsList[14],VectorsList[15],VectorsList[16],VectorsList[17],VectorsList[18],VectorsList[19]]

        error = 0
        if ParentID == '': print 'Object has no parent'
        if vert != []: setVector( vert, 0, 0, ObjectID, 0 )
        else: print 'ERROR: Vector Object has no Vertices'; error = 1
        if error == 0:
            if normal != []: setVector( normal, 1, 0, ObjectID, 0 )
            else: print 'Normals are nonexistant'
            if UVs != [[],[],[],[],[],[],[],[]]:
                for channel, UV in enumerate(UVs): setVector( UV, 2, 0, ObjectID, channel )
            else: print "UV's are nonexistant"
            
            if trans_vert != []: setVector( trans_vert, 0, 1, ObjectID, 0 )
            else: print 'Vertice Transforms are nonexistant'
            if trans_normal != []: setVector( trans_normal, 1, 1, ObjectID, 0 )
            else: print 'Normal Transforms are nonexistant'
            if trans_UVs != [[],[],[],[],[],[],[],[]]:
                for channel, TransUV in enumerate(trans_UVs): setVector( TransUV, 2, 1, ObjectID, channel )
            else: print "UV Transforms are nonexistant"

            if PrimitivesList != []: setPrimitives( PrimitivesList, ObjectID )
            else: print 'Object has no primitives'

            setBasicObject(ObjectID, ObjectName, ParentID)
        else: print '--Object cannot be logged'
        
    if VectorsList == [] and BonesList != []:
        if PrimitivesList != []: print 'ERROR: Bone Object must not contain primitives'
        else: pass #TODO
    if VectorsList != [] and BonesList != []:
        if PrimitivesList != []: print 'ERROR: Primitive Object must not contain bones'
        else: print 'ERROR: Vector Object must not contain bones'
    if VectorsList == [] and BonesList == []:
        if PrimitivesList != []:
            print 'Primitive Object uses global vectors'
            setPrimitives( PrimitivesList, ObjectID )
            setBasicObject(ObjectID, ObjectName, ParentID)
        else: print 'ERROR: Please supply a Primitive Object, Vector Object, or Bone Object'

def getObject( ObjectID, Global ):
    Name, Parent = getBasicObject( ObjectID )

    OID = ObjectID
    if Global == 1: OID ='global'
    if Global != '':
        VectorsList = [
        getVector(0, 0, OID, 0), getVector(1, 0, OID, 0),
        getVector(2, 0, OID, 0), getVector(2, 0, OID, 1),
        getVector(2, 0, OID, 2), getVector(2, 0, OID, 3),
        getVector(2, 0, OID, 4), getVector(2, 0, OID, 5),
        getVector(2, 0, OID, 6), getVector(2, 0, OID, 7),
        getVector(0, 1, OID, 0), getVector(1, 1, OID, 0),
        getVector(2, 1, OID, 0), getVector(2, 1, OID, 1),
        getVector(2, 1, OID, 2), getVector(2, 1, OID, 3),
        getVector(2, 1, OID, 4), getVector(2, 1, OID, 5),
        getVector(2, 1, OID, 6), getVector(2, 1, OID, 7)
        ]
        PrimitivesList = getPrimitives( ObjectID )
        
    if Global == '': PrimitivesList = getPrimitives( ObjectID )
    
    BoneList = []#TODO
    
    return Name, Parent, VectorsList, PrimitivesList, BoneList

def getObjectIDs(): #defined for exporting
    IDs = []
    tmpr.seek(0,0)
    lines = tmpr.readlines()
    for line in lines:
        if line.split()[1] == 'object':
            IDs.append(line.split()[2])
    return IDs

#TMP format specs... DO NOT CHANGE!
#these are the main secs defined for every plugin when converting to TMP

def getSpecs():
    tmpr.seek(0,0)
    
    global vecs_global
    global vecs_transf
    vecs_global = 0
    vecs_transf = 0
    
    lines = tmpr.readlines()
    for line in lines:
        if line.split()[0] == '!':
            if line.split()[1] == 'vectors':
                for Type in (line.split()[2]).split('|'):
                    if Type == 'global': vecs_global = 1
                    if Type == 'transf': vecs_transf = 1
    
def setSpecs(specList): 
    pass
    vecs = []
    for spec in specList:
        if spec.split('_')[0] == 'vecs': vecs.append(spec.split('_')[1])

    if len(vecs) > 0: tmpw.write( '! vectors ' + '|'.join(vecs) + '\n')

    print 'set specs: ' + ' '.join(specList)
